<?php

namespace App\Http\Controllers\Api;

use App\Http\Resources\Images;
use App\Http\Resources\UserAddress;
use App\Models\CustomerDetail;
use App\Models\Image;
use App\Models\Order;
use App\Services\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class UserController extends Controller
{
    /**
     * 个人中心
     */
    public function index(Request $request)
    {
        $user = Auth::user();

        return Api::success([
            'id' => $user->id,
            'username' => $user->username,
            'group_id' => $user->group_id,
            'avatar' => $user->avatar ? Images::make($user->avatar) : null,
            'orders' => [
                'un_paid' => Order::status('pay')->where('customer_id', $user->id)->count(),
                'un_received' => Order::status('ship')->where('customer_id', $user->id)->count(),
                'un_reviewed' => Order::status('comment')->where('customer_id', $user->id)->count(),
                'refund' => Order::status('refund')->where('customer_id', $user->id)->count(),
            ],
        ]);
    }

    /**
     * 权限
     */
    public function permission(Request $request)
    {
        $base = [
            ['id' => 1, 'name' => '会员标识', 'enable' => 1],
            ['id' => 2, 'name' => '会员日活动', 'enable' => 1],
            ['id' => 3, 'name' => '专享优惠', 'enable' => 1],
            ['id' => 4, 'name' => '退货无忧', 'enable' => 1],
            ['id' => 5, 'name' => '全场免邮', 'enable' => 1],
            ['id' => 6, 'name' => '购物送积分', 'enable' => 0],
        ];

        if (Auth::user()->group_id) {
            $base = array_merge($base, [
                ['id' => 7, 'name' => '批发优惠', 'enable' => 1],
                ['id' => 8, 'name' => '高端定制', 'enable' => 1],
            ]);
        }

        return Api::success($base);
    }

    /**
     * 用户密码修改
     */
    public function password(Request $request)
    {
        $data = $request->all(['password', 'password_confirm']);

        if ($data['password'] !== $data['password_confirm']) {
            return Api::msg('api.password.confirm_failure');
        }
        $user = Auth::user();
        $user->password = bcrypt(password('password'));
        $user->verify_at = now();
        try {
            $user->save();
        } catch (\Exception $exception) {
            return Api::msg('api.password.failure');
        }
        return Api::msg('api.password.success');
    }

    /**
     * 我的优惠券
     */
    public function coupons(Request $request)
    {
        return Api::success(Auth::user());
    }

    /**
     * 设置默认地址
     */
    public function defaultAddress(Request $request)
    {
        $id = $request->post('address');

        \App\Models\UserAddress::query()
            ->where('customer_id', Auth::id())
            ->update(['is_default' => 0]);

        \App\Models\UserAddress::query()
            ->where('customer_id', Auth::id())
            ->where('id', $id)
            ->update(['is_default' => 1]);

        return Api::success();
    }

    /**
     * 添加地址
     */
    public function address(Request $request)
    {
        $data = $request->all([
            'province', # 省
            'city', # 市
            'district', # 县/区
            'address', # 详细地址
            'is_default', # 是否默认
            'contact_name', # 联系人
            'contact_phone', # 联系电话
        ]);

        $isDefault = $data['is_default'] ? 1 : 0;

        if ($isDefault) {
            \App\Models\UserAddress::query()
                ->where('customer_id', Auth::id())
                ->update(['is_default' => 0]);
        }

        $address = \App\Models\UserAddress::create([
            'customer_id' => Auth::id(), # 省
            'province_id' => $data['province'], # 省
            'city_id' => $data['city'], # 市
            'district_id' => $data['district'], # 县/区
            'address' => $data['address'], # 详细地址
            'is_default' => $isDefault, # 是否默认
            'contact_name' => $data['contact_name'], # 联系人
            'contact_phone' => $data['contact_phone'], # 联系电话
        ]);

        return Api::success(UserAddress::make($address));
    }

    /**
     * 地址列表
     */
    public function getAddress()
    {
        return Api::success(UserAddress::collection(Auth::user()->addresses));
    }

    /**
     * 个人详细信息
     */
    public function detail()
    {
        $user = Auth::user();

        $detail = $user->detail;

        return Api::success([
            'id' => $user->id,
            'username' => $detail->nickname ?: $user->username,
            'group_id' => $user->group_id,
            'avatar' => $user->avatar ? Images::make($user->avatar) : null,
            'summary' => $detail->summary,
            'sex' => $detail->sex,
        ]);
    }

    /**
     * 更新个人信息
     */
    public function update(Request $request)
    {
        $data = $request->only([
            'avatar',
            'username',
            'summary',
            'sex',
        ]);

        $detail = CustomerDetail::query()->firstOrCreate([
            'customer_id' => Auth::id(),
        ]);

        if (isset($data['summary'])) {
            $update['summary'] = $data['summary'];
        }

        if (isset($data['sex'])) {
            $update['sex'] = $data['sex'];
        }

        if (isset($data['username'])) {
            $update['nickname'] = $data['username'];

            Auth::user()->update([
                'username' => $data['username'],
            ]);
        }

        if (isset($data['avatar'])) {
            Auth::user()->avatar()->delete();
            Image::query()->create([
                'type' => Image::CUSTOMER_AVATAR,
                'type_id' => Auth::id(),
                'path' => $data['avatar'],
            ]);
        }

        if (isset($update)) {
            $detail->update($update);
        }

        return $this->detail();
    }
}
